package com.by.toolkitspring.customizeannotation;

import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.annotation.AnnotationAttributes;
import org.springframework.core.type.AnnotationMetadata;
import org.springframework.core.type.StandardAnnotationMetadata;

import java.lang.annotation.Annotation;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 自定义注解注册
 *
 * @author YanBingHao
 * @since 2023/12/25
 */
@Slf4j
@SuppressWarnings({"unused", "unchecked"})
public class ByScannerRegistrar implements ImportBeanDefinitionRegistrar {

    private static final List<String> BASE_PACKAGE_LIST = Lists.newArrayList();

    private static final List<Class<? extends Annotation>> ANNOTATION_CLASS_LIST = Lists.newArrayList();

    private static final String BASE_PACKAGE_FIELD_NAME = "basePackage";

    private static final String ANNOTATION_CLASS_FIELD_NAME = "annotationClass";

    @Override
    public void registerBeanDefinitions(AnnotationMetadata annotationMetadata, BeanDefinitionRegistry beanDefinitionRegistry) {
        //获取所有注解的属性和值
        AnnotationAttributes annoAttrs = AnnotationAttributes.fromMap(annotationMetadata.getAnnotationAttributes(ByScan.class.getName()));
        if (Objects.isNull(annoAttrs)) {
            //BASE_PACKAGE_LIST.add(((StandardAnnotationMetadata) annotationMetadata).getIntrospectedClass().getPackage().getName());
            return;
        }

        //获取到basePackage的值
        String[] basePackages = annoAttrs.getStringArray(BASE_PACKAGE_FIELD_NAME);
        //如果没有设置basePackage 扫描路径,就扫描对应包下面的值
        BASE_PACKAGE_LIST.addAll(basePackages.length == 0
                ? List.of(((StandardAnnotationMetadata) annotationMetadata).getIntrospectedClass().getPackage().getName())
                : List.of(basePackages));

        Class<? extends Annotation>[] classArray = (Class<? extends Annotation>[]) annoAttrs.getClassArray(ANNOTATION_CLASS_FIELD_NAME);
        ANNOTATION_CLASS_LIST.addAll(Stream.of(classArray).collect(Collectors.toList()));

        log.info("basePackage: {}", BASE_PACKAGE_LIST);
        log.info("annotationClass: {}", ANNOTATION_CLASS_LIST);
    }

    public static List<String> getBasePackageList() {
        return BASE_PACKAGE_LIST;
    }

    public static List<Class<? extends Annotation>> getAnnotationClassList() {
        return ANNOTATION_CLASS_LIST;
    }

}
